#ifndef __Step_moter_H
#define __Step_moter_H
#define CPU_SELECT_AT32F415XX
#ifdef CPU_SELECT_AT32F415XX
#include "at32f415.h"
#endif
/**Hardware abstract for structure define**/
#define STEP_MOTOR_MEMBER_PWM \
volatile tmr_channel_select_type Channel;\
tmr_type *TIM;\

#define STEP_MOTOR_MEMBER_DIR_GPIO \
gpio_type *DIR_GPIO_Port;\
uint16_t      DIR_GPIO_Pin;\
/**Hardware control abstract**/


#define STEP_MOTOR_DIR_MASK       0x00000002
#define STEP_MOTOR_DIR_FORWARD    0x00000002
#define STEP_MOTOR_DIR_BACKWARD   0x00000000

#define STEP_MOTOR_STATE_MASK     0x00000004
#define STEP_MOTOR_STATE_RUN      0x00000004
#define STEP_MOTOR_STATE_STOP     0x00000000

#define STEP_MOTOR_FLAGS(pmotor)   ((pmotor)->flags)
#define STEP_MOTOR_FLAGS_MASK(pmotor,mask)   (((pmotor)->flags) & (mask))

#define Motor_Circle (double)(251.3274)
#define Distance_To_Step( Distance )  (uint32_t)( ((Distance) / Motor_Circle) * 6400 )

#define Turn_Circle_Angle_Step 340

#define CAR_MOTION_TYPE_MASK                     0x00000007
#define CAR_MOTION_TYPE_TRANSLATION_FORWARD      0x00000001
#define CAR_MOTION_TYPE_TRANSLATION_BACKWARD     0x00000002
#define CAR_MOTION_TYPE_TRANSLATION_LEFT         0x00000003
#define CAR_MOTION_TYPE_TRANSLATION_RIGHT        0x00000004
#define CAR_MOTION_TYPE_ROTATION_CLOCKWISE       0x00000005
#define CAR_MOTION_TYPE_ROTATION_ANITICLOCKWISE  0x00000006

#define Angle_Step (uint32_t) 360

typedef struct
{
    volatile int state ;
    volatile int Step ;
    volatile int Check_Setp;
    volatile int32_t Target_Step ;
    volatile int32_t Target_MicroStepPerSencond;

    volatile uint16_t pre_f;
    volatile uint16_t acce;
    volatile uint8_t microstepping_level;

    volatile uint32_t TIM_CNT_FREQ;// CLK/PSC

    STEP_MOTOR_MEMBER_PWM
    
    STEP_MOTOR_MEMBER_DIR_GPIO

    volatile uint16_t flags;
} StepMotor;


#define FORWARD  1 
#define REVERSE  0
#define RUN 1 
#define STOP 0

void Step_moter_Init(void) ;
void Step_moter_OnePeriod(  const StepMotor *aStepMotor, uint8_t direct  ) ;

void StepMotor_RunStep(StepMotor *motor, int32_t target, int32_t microStepPerSecond,uint16_t attr);
void StepMotor_RunSpeed(StepMotor *motor, int32_t microStepPerSecond,uint16_t attr);
void StepMotor_SetSpeed(StepMotor* motor, int32_t microStepPerSecond);
void StepMotor_Stop(StepMotor *motor);

void StepMotorHandler(StepMotor *aStepMotor);

#endif
